package com.ustc.hewei.detectbeats.net;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import lombok.extern.slf4j.Slf4j;

/**
* @description: 注册中心网络的handler
* @author hewei
* @date 2022/8/17 20:11
* @version 1.0
*/

@Slf4j
@ChannelHandler.Sharable
public class ChannelNotifyHandler extends ChannelInboundHandlerAdapter {
    private NotifyHandler notifyHandler;

    public ChannelNotifyHandler(NotifyHandler notifyHandler) {
        this.notifyHandler = notifyHandler;
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) {
        log.info("注册中心收到通知 {}", msg);
        ByteBuf receive = (ByteBuf) msg;
        byte[] res = new byte[receive.readableBytes()];
        receive.readBytes(res);
        receive.release();
        // resp是要返回给服务端的信息
        byte[] resp = notifyHandler.handler(res);
        ByteBuf buffer = Unpooled.buffer(resp.length);
        buffer.writeBytes(resp);
        ctx.write(buffer);
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        ctx.flush();
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        log.error("出现异常，即将关闭网络通信! {}", cause.getMessage());
        ctx.close();
    }
}
